package com.hsl.housaileibot001.controller;

import com.hsl.housaileibot001.common.Result;
import com.hsl.housaileibot001.document.MockQuestion;
import com.hsl.housaileibot001.model.vo.PracticeQuestionVO;
import com.hsl.housaileibot001.service.MockQuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 刷题控制器
 */
@Tag(name = "刷题接口", description = "刷题相关接口")
@RestController
@RequestMapping("/practice")
public class PracticeController {

    @Resource
    private MockQuestionService mockQuestionService;

    /**
     * 获取刷题题目列表
     * 将所有 MockQuestion 中的题目项扁平化返回
     * 
     * @param interviewQuestionId 面试题ID（可选，如果提供则只返回该面试题的题目）
     * @return 题目列表
     */
    @Operation(summary = "获取刷题题目列表", description = "获取所有可用于刷题的题目，返回扁平化的题目列表")
    @GetMapping("/questions")
    public Result<List<PracticeQuestionVO>> getPracticeQuestions(
            @Parameter(description = "面试题ID（可选）") @RequestParam(required = false) Long interviewQuestionId) {
        try {
            List<MockQuestion> mockQuestions;
            
            if (interviewQuestionId != null) {
                // 获取指定面试题的题目
                mockQuestions = mockQuestionService.findActiveByInterviewQuestionId(interviewQuestionId);
            } else {
                // 获取所有有效的题目
                mockQuestions = mockQuestionService.findByStatus("ACTIVE");
            }
            
            // 扁平化题目列表
            List<PracticeQuestionVO> practiceQuestions = new ArrayList<>();
            int questionIndex = 1;
            
            for (MockQuestion mockQuestion : mockQuestions) {
                if (mockQuestion.getQuestionItems() != null) {
                    for (MockQuestion.QuestionItem item : mockQuestion.getQuestionItems()) {
                        PracticeQuestionVO vo = new PracticeQuestionVO();
                        vo.setId(mockQuestion.getId() + "_" + (questionIndex - 1));
                        vo.setQuestionIndex(questionIndex++);
                        vo.setInterviewQuestionId(mockQuestion.getInterviewQuestionId());
                        vo.setOverview(mockQuestion.getOverview());
                        vo.setQuestion(item.getQuestion());
                        vo.setOptions(item.getOptions());
                        vo.setAnswer(item.getAnswer());
                        vo.setExplanation(item.getExplanation());
                        practiceQuestions.add(vo);
                    }
                }
            }
            
            return Result.success(practiceQuestions);
        } catch (Exception e) {
            return Result.error("获取题目列表失败：" + e.getMessage());
        }
    }

}

